package org.myontology.logging;

import java.sql.Timestamp;

import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.myontology.controller.AttributeHolder;
import org.myontology.db.SessionWrapper;
import org.myontology.helpers.TypedURI;
import org.myontology.users.Login;
import org.openrdf.model.URI;

public class ElementLogging extends SessionWrapper {

	public ElementLogging(Session session) {
		super(session);
	}

	public void logView(URI uri, AttributeHolder attributes) {
		log(uri,attributes,LogLine.VIEW);
	}
	public void logEdit(URI uri, AttributeHolder attributes) {
		log(uri,attributes,LogLine.EDIT);
	}
	public void logCreate(URI uri, AttributeHolder attributes) {
		log(uri,attributes,LogLine.CREATE);
	}
	public void logDelete(URI u, AttributeHolder attributes) {
		TypedURI uri = new TypedURI(u);
		
		Query q = createQuery("DELETE FROM LogLine WHERE name=? AND type=?").setString(0, uri.getLocalName()).setString(1, uri.getType());
		q.executeUpdate();
		
//
//
//		
//		LogLine line = new LogLine();
//		line.setAction(action);
//		line.setTime(new Timestamp(System.currentTimeMillis()));
//		line.setUser(user);
//		line.setUri(uri.stringValue());
//		line.setType(uri.getType());
//		line.setName(uri.getLocalName());
//		line.setVersion(uri.getVersion());
//		save(line);
	}
	
	
	private void log(URI u, AttributeHolder attributes, int action) {
		TypedURI uri = new TypedURI(u);
		String user = Login.CURRENT_USER.getValue(attributes);
		if (user==null) {
			user="anonymous";
		}
		


		
		LogLine line = new LogLine();
		line.setAction(action);
		line.setTime(new Timestamp(System.currentTimeMillis()));
		line.setUser(user);
		line.setUri(uri.stringValue());
		line.setType(uri.getType());
		line.setName(uri.getLocalName());
		line.setVersion(uri.getVersion());
		save(line);
	}
	
	

}
